package com.huarui.code.dao.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.ewaf.framework.dao.impl.BaseDaoImpl;
import com.huarui.code.dao.ICodeGenericDao;
import com.huarui.code.model.CodeGeneric;

public class CodeGenericDaoImpl extends BaseDaoImpl implements ICodeGenericDao{

	@Override
	public String getNewCode(Integer companyId, String documentName) {
		Date currentTime = Calendar.getInstance().getTime();
		String fm_currentTime = format(currentTime);
		CodeGeneric cd = getCodeGenericByMap(companyId, documentName, fm_currentTime);

		String preStr = CodeGeneric.DocumentMap.get(documentName);
		if(StringUtils.isBlank(preStr)) {
			throw new RuntimeException("单据名错误...");
		}
		
		if (cd == null) {
			CodeGeneric c = new CodeGeneric();
			c.setCompanyId(companyId);
			c.setDocumentName(documentName);
			c.setGmtDate(currentTime);
			int lastNumber = 1;
			c.setLastNumber(lastNumber);
			c.setLastCode(preStr + getLastCode(currentTime, lastNumber));
			this.create(c);
			return c.getLastCode();
		} 
		
		int lastNumber = cd.getLastNumber() + 1;
		cd.setLastNumber(lastNumber);
		cd.setLastCode(preStr + getLastCode(currentTime, lastNumber));
		this.update(cd);
		return cd.getLastCode();
	}

	/**
	 * 根据公司ID,单据名称，当前日期查询出唯一的对象
	 * @param companyId 公司ID
	 * @param documentName 单据名称
	 * @param currentTime 当前日期
	 * @return
	 */
	private CodeGeneric getCodeGenericByMap(Integer companyId, String documentName, String currentTime) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("companyId", companyId);
		paramMap.put("documentName", documentName);
		paramMap.put("gmtDate", currentTime);
		CodeGeneric c = (CodeGeneric)this.getSqlMapClientTemplate().queryForObject(namespace + ".getMaxLastNums", paramMap);
		return c;
	}
	
	/**
	 * 得到当前时间的最大数字编码
	 * @param currentTime 当前时间
	 * @param lastNumber 最大数字
	 * @return
	 */
	private String getLastCode(Date currentTime, Integer lastNumber) {
		DateFormat fm = new SimpleDateFormat("yyyyMMdd");
		String lastCode = fm.format(currentTime) ;
		String numStr = lastNumber.toString();
		//不满足3位时，在前面加0
		while (numStr.length() < 3) {
			numStr = "0" + numStr;
		}
		lastCode += numStr;
		return lastCode;
	}
	
	/**
	 * 格式化成定制样式
	 * @param date 日期
	 * @return
	 */
	private String format(Date date) {
		DateFormat fm = new SimpleDateFormat("yyyy-MM-dd");
		String mt = fm.format(date);
		return mt;
	}
}
